#!/bin/bash

# 计时器API测试脚本
# 使用方法: ./test-timer-api.sh

BASE_URL="http://localhost:8080/api"
TOKEN=""

echo "========================================="
echo "计时器API测试"
echo "========================================="
echo ""

# 1. 登录获取token
echo "1. 登录获取token..."
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/user/login" \
  -H "Content-Type: application/json" \
  -d '{
    "username": "chenfangyuan",
    "password": "123456"
  }')

echo "登录响应: $LOGIN_RESPONSE"
TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"data":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "❌ 登录失败，无法获取token"
  exit 1
fi

echo "✅ 登录成功，Token: ${TOKEN:0:20}..."
echo ""

# 2. 获取当前计时器（应该为空）
echo "2. 获取当前计时器..."
curl -s -X GET "$BASE_URL/timer/current" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 3. 开始计时（使用taskId=1）
echo "3. 开始计时（taskId=1）..."
START_RESPONSE=$(curl -s -X POST "$BASE_URL/timer/start" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "taskId": 1
  }')

echo "$START_RESPONSE" | jq '.'
RECORD_ID=$(echo $START_RESPONSE | grep -o '"recordId":[0-9]*' | cut -d':' -f2)
echo "记录ID: $RECORD_ID"
echo ""

# 4. 再次获取当前计时器（应该有数据）
echo "4. 获取当前计时器..."
curl -s -X GET "$BASE_URL/timer/current" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 5. 等待3秒
echo "5. 等待3秒..."
sleep 3
echo ""

# 6. 暂停计时
echo "6. 暂停计时..."
curl -s -X POST "$BASE_URL/timer/$RECORD_ID/pause" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 7. 等待2秒
echo "7. 等待2秒..."
sleep 2
echo ""

# 8. 继续计时
echo "8. 继续计时..."
curl -s -X POST "$BASE_URL/timer/$RECORD_ID/resume" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 9. 等待2秒
echo "9. 等待2秒..."
sleep 2
echo ""

# 10. 停止计时
echo "10. 停止计时..."
curl -s -X POST "$BASE_URL/timer/$RECORD_ID/stop" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 11. 获取计时记录列表
echo "11. 获取计时记录列表..."
curl -s -X GET "$BASE_URL/timer/records" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

# 12. 获取统计信息
echo "12. 获取统计信息..."
curl -s -X GET "$BASE_URL/timer/statistics?period=week" \
  -H "Authorization: Bearer $TOKEN" | jq '.'
echo ""

echo "========================================="
echo "测试完成！"
echo "========================================="
